<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="统计日期" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          :type="datePickerType"
          placeholder="请选择统计日期"
          value-format="yyyy-MM"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="统计维度">
        <el-select v-model="queryParams.type" placeholder="请选择统计维度" @change="handleQuery">
          <el-option label="月份维度" value="month" />
          <el-option label="年份维度" value="year" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>教师课时统计</span>
            </div>
          </template>
          <div ref="teacherChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>学生积分统计</span>
            </div>
          </template>
          <div ref="studentChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>订单统计</span>
            </div>
          </template>
          <div ref="orderChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template slot="header">
            <div class="card-header">
              <span>收入统计</span>
            </div>
          </template>
          <div ref="incomeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getYsgStatistic } from "@/api/ysg/statistic"
import * as echarts from "echarts"

export default {
  name: "Statistic",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        date: new Date().toISOString().slice(0, 7), // 默认当前月份
        type: 'month' // 默认月份维度
      },
      // 教师统计图表实例
      teacherChart: null,
      // 学生统计图表实例
      studentChart: null,
      // 订单统计图表实例
      orderChart: null,
      // 收入统计图表实例
      incomeChart: null,
      // 统计数据
      statisticData: {
        teacherStatisticList: [],
        studentStatisticList: [],
        orderStatisticList: [],
        incomeStatisticList: []
      }
    }
  },
  computed: {
    // 根据统计维度动态切换日期选择器类型
    datePickerType() {
      return this.queryParams.type === 'year' ? 'year' : 'month'
    }
  },
  mounted() {
    this.initCharts()
    this.getList()
    window.addEventListener("resize", this.handleResize)
  },
  beforeDestroy() {
    if (this.teacherChart) {
      this.teacherChart.dispose()
    }
    if (this.studentChart) {
      this.studentChart.dispose()
    }
    if (this.orderChart) {
      this.orderChart.dispose()
    }
    if (this.incomeChart) {
      this.incomeChart.dispose()
    }
    window.removeEventListener("resize", this.handleResize)
  },
  methods: {
    /** 初始化图表 */
    initCharts() {
      this.teacherChart = echarts.init(this.$refs.teacherChart)
      this.studentChart = echarts.init(this.$refs.studentChart)
      this.orderChart = echarts.init(this.$refs.orderChart)
      this.incomeChart = echarts.init(this.$refs.incomeChart)
    },
    /** 查询统计数据 */
    getList() {
      this.loading = true
      getYsgStatistic(this.queryParams).then(response => {
        this.statisticData = response.data
        this.loading = false
        this.renderCharts()
      })
    },
    /** 渲染图表 */
    renderCharts() {
      this.renderTeacherChart()
      this.renderStudentChart()
      this.renderOrderChart()
      this.renderIncomeChart()
    },
    /** 渲染教师课时统计图表 */
    renderTeacherChart() {
      const teacherData = this.statisticData.teacherStatisticList
      const teacherNames = teacherData.map(item => item.teacherName)
      const doneHours = teacherData.map(item => item.teacherDoneHour)
      const totalHours = teacherData.map(item => item.teacherTotalHour)
      
      // 计算未完成课时
      const remainingHours = totalHours.map((total, index) => {
        return Math.max(0, total - doneHours[index])
      })
      
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            result += params[0].seriesName + ': ' + params[0].value + '<br/>'
            result += params[1].seriesName + ': ' + params[1].value + '<br/>'
            result += '总课时: ' + (params[0].value + params[1].value)
            return result
          }
        },
        legend: {
          data: ["已完成课时", "未完成课时"]
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: teacherNames,
          axisLabel: {
            interval: 0,
            rotate: 30
          },
          boundaryGap: [0, 0.01] // 柱子居中显示
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "已完成课时",
            type: "bar",
            data: doneHours,
            barMaxWidth: 50, // 限制最大宽度，避免数据过少时柱子太宽
            stack: "total", // 堆叠组名称
            itemStyle: {
              color: "#36a2eb" // 蓝色
            }
          },
          {
            name: "未完成课时",
            type: "bar",
            data: remainingHours,
            stack: "total", // 同一堆叠组
            itemStyle: {
              color: "#ff6b6b" // 红色，更醒目
            }
          }
        ]
      }
      this.teacherChart.setOption(option)
    },
    /** 渲染学生积分统计图表 */
    renderStudentChart() {
      const studentData = this.statisticData.studentStatisticList
      const studentNames = studentData.map(item => item.studentName)
      const scores = studentData.map(item => item.totalScore)
      
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow"
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: studentNames,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "积分",
            type: "bar",
            data: scores,
            barMaxWidth: 50, // 限制最大宽度，避免数据过少时柱子太宽
            itemStyle: {
              color: {
                type: 'gradient',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#4facfe' // 渐变蓝色开始
                }, {
                  offset: 1, color: '#00f2fe' // 渐变蓝色结束
                }]
              }
            }
          }
        ]
      }
      this.studentChart.setOption(option)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.date = new Date().toISOString().slice(0, 7)
      this.queryParams.type = 'month' // 默认月份维度
      this.getList()
    },
    /** 渲染订单统计图表 */
    renderOrderChart() {
      const orderData = this.statisticData.orderStatisticList
      
      // 定义状态映射
      const statusMap = {
        '0': '待支付',
        '1': '已支付',
        '2': '已取消',
        '3': '已完成'
      }
      
      // 准备数据
      const statuses = Object.values(statusMap)
      const orderCounts = statuses.map(status => {
        const item = orderData.find(data => statusMap[data.status] === status)
        return item ? item.orderCount : 0
      })
      const totalAmounts = statuses.map(status => {
        const item = orderData.find(data => statusMap[data.status] === status)
        return item ? item.totalAmount : 0
      })
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['订单数量', '订单金额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: statuses
        },
        yAxis: [
          {
            type: 'value',
            name: '订单数量',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '订单金额',
            axisLabel: {
              formatter: '{value} 元'
            }
          }
        ],
        series: [
          {
            name: '订单数量',
            type: 'bar',
            data: orderCounts,
            barMaxWidth: 50,
            itemStyle: {
              color: {
                type: 'gradient',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#4facfe' // 渐变蓝色开始
                }, {
                  offset: 1, color: '#00f2fe' // 渐变蓝色结束
                }]
              }
            }
          },
          {
            name: '订单金额',
            type: 'bar',
            yAxisIndex: 1,
            data: totalAmounts,
            barMaxWidth: 50,
            itemStyle: {
              color: {
                type: 'gradient',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: '#fa709a' // 渐变粉色开始
                }, {
                  offset: 1, color: '#fee140' // 渐变黄色结束
                }]
              }
            }
          }
        ]
      }
      this.orderChart.setOption(option)
    },
    /** 渲染收入统计图表 */
    renderIncomeChart() {
      const incomeData = this.statisticData.incomeStatisticList
      
      // 准备数据
      const dates = incomeData.map(item => item.date)
      const incomes = incomeData.map(item => item.income)
      const orderCounts = incomeData.map(item => item.orderCount)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            result += params[0].seriesName + ': ' + params[0].value + ' 元<br/>'
            result += params[1].seriesName + ': ' + params[1].value + ' 单'
            return result
          }
        },
        legend: {
          data: ['收入金额', '订单数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '收入金额',
            axisLabel: {
              formatter: '{value} 元'
            }
          },
          {
            type: 'value',
            name: '订单数量',
            axisLabel: {
              formatter: '{value} 单'
            }
          }
        ],
        series: [
          {
            name: '收入金额',
            type: 'line',
            smooth: true,
            data: incomes,
            itemStyle: {
              color: '#4facfe'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(79, 172, 254, 0.5)'
                }, {
                  offset: 1, color: 'rgba(79, 172, 254, 0.1)'
                }]
              }
            }
          },
          {
            name: '订单数量',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            data: orderCounts,
            itemStyle: {
              color: '#fa709a'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(250, 112, 154, 0.5)'
                }, {
                  offset: 1, color: 'rgba(250, 112, 154, 0.1)'
                }]
              }
            }
          }
        ]
      }
      this.incomeChart.setOption(option)
    },
    /** 窗口大小变化时重新渲染图表 */
    handleResize() {
      if (this.teacherChart) {
        this.teacherChart.resize()
      }
      if (this.studentChart) {
        this.studentChart.resize()
      }
      if (this.orderChart) {
        this.orderChart.resize()
      }
      if (this.incomeChart) {
        this.incomeChart.resize()
      }
    }
  }
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 400px;
  width: 100%;
}
</style>
